(function() {
  app.controller('reportCtrl', function($state, $scope, tradeApi, returnData, $rootScope, $interval, header_m, local_m, $timeout) {
    header_m.set({
      css_l: {
        name: 'icon-user'
      },
      fun_l: function() {
        local_m
          .set('my_index_back', 'report');
        $state.go('my_index');
      },
      css_r: {
        name: 'refresh@2x'
      },
      fun_r: function() {
        $('#header_right').removeClass('reload-ate');
        $timeout(function() {
          $('#header_right').addClass('reload-ate');
        });
      }
    });

    $scope.condition = local_m.get('report_condition') || [
      {
        head: '盈/亏',
        options: [
          { txt: '全部', value: '' },
          { txt: '盈利', value: '0' },
          { txt: '亏损', value: '1' },
        ],
        default: { txt: '全部', value: '' },
      },

      {
        head: '创建日期',
        options: [
          { txt: '全部', value: '20170901' },
          { txt: '7天之内', value: 7 },
          { txt: '15天之内', value: 15 },
        ],
        default: { txt: '7天之内', value: 7 },
      }
    ];

    local_m.set('report_condition', '');

    $scope.init = function() {
      $scope.client_purchase_info_list();
    };

    $scope.client_purchase_info_list = function() {
      var data = returnData.dateSet($scope.condition[1].default.value);
      data.start_date = data.startdate;
      data.end_date = data.enddate;
      tradeApi.query({
        funcId: '300026',
        data: data
      }).then(function(res) {
        if (!res) return;
        var result = res.filter(function(item, i) {
          if ((item.contract_status === '1' || item.contract_status === '9') && item.close_status === '2') return true;
        });
        if ($scope.condition[0].default.value === '') return $scope.client_purchase_list = result;
        $scope.client_purchase_list = result.filter(function(item, i) {
          if (item.income_balance >= 0 && $scope.condition[0].default.value === '0') return true;
          if (item.income_balance < 0 && $scope.condition[0].default.value === '1') return true;
        });
      });
    };

    $scope.go_detail = function(item) {
      $scope.storage.local('report_dl', item);
      local_m.set('report_condition', $scope.condition);
      $state.go('details-report');
    };

    var timer = $interval(function() {
      $scope.init();
    }, 5000);
    $scope.$on('$destroy', function() {
      $interval.cancel(timer);
      timer = null;
    });

  });

  app.filter('check_report', function() {
    return function(input) {
      var flag = true;
      angular.forEach(input, function(item) {
        if (item.close_type !== '0' || item.close_status === '2') {
          flag = false;
        }
      });
      return flag;
    };
  });
})();
